<%page expression_filter="h"/>
<%!
import logging
import json
from django.contrib.staticfiles.storage import staticfiles_storage
from common.djangoapps.pipeline_mako import compressed_css, compressed_js
from django.utils.translation import get_language_bidi
from mako.exceptions import TemplateLookupException
from common.djangoapps.edxmako.shortcuts import marketing_link

from openedx.core.djangolib.js_utils import js_escaped_string, dump_js_escaped_json
from openedx.core.djangolib.markup import HTML
from openedx.core.djangoapps.site_configuration.helpers import (
  page_title_breadcrumbs,
  get_value,
)

from openedx.core.djangoapps.theming.helpers import (
  get_template_path,
  is_request_in_themed_site,
)
from lms.djangoapps.certificates.api import get_asset_url_by_slug
from webpack_loader.templatetags.webpack_loader import render_bundle
logger = logging.getLogger(__name__)
%>

<%def name="marketing_link(name)"><%
    link = marketing_link(name)
    return "/" if link == "#" else link
%></%def>

<%def name='url(file, raw=False)'><%
try:
    url = staticfiles_storage.url(file)
except:
    url = file
## HTML-escaping must be handled by caller
%>${url | n, decode.utf8}${"?raw" if raw else ""}</%def>

<%def name='certificate_asset_url(slug)'><%
try:
    url = get_asset_url_by_slug(slug)
except:
    url = ''
## HTML-escaping must be handled by caller
%>${url | n, decode.utf8}</%def>

<%def name='css(group, raw=False)'>
  <%
      rtl_group = '{}-rtl'.format(group)

      if get_language_bidi() and rtl_group in settings.PIPELINE['STYLESHEETS']:
        group = rtl_group
  %>

  % if settings.PIPELINE['PIPELINE_ENABLED']:
    ${compressed_css(group, raw=raw) | n, decode.utf8}
  % else:
    % for filename in settings.PIPELINE['STYLESHEETS'][group]['source_filenames']:
      <link rel="stylesheet" href="${staticfiles_storage.url(filename.replace('.scss', '.css'))}${"?raw" if raw else ""}" type="text/css" media="all" / >
    % endfor
  %endif
</%def>

<%def name='js(group)'>
  % if settings.PIPELINE['PIPELINE_ENABLED']:
    ${compressed_js(group) | n, decode.utf8}
  % else:
    % for filename in settings.PIPELINE['JAVASCRIPT'][group]['source_filenames']:
      <script type="text/javascript" src="${staticfiles_storage.url(filename.replace('.coffee', '.js'))}"></script>
    % endfor
  %endif
</%def>

## A language-direction indicator, suitable for use in class="" attributes,
## for example:
##
##      <body class="${dir_rtl()}">
##
<%def name="dir_rtl()"><%
    return 'rtl' if get_language_bidi() else 'ltr'
%></%def>

<%def name="include(path)"><%
from django.conf import settings
from django.template.engine import Engine
from django.template import TemplateDoesNotExist
from django.template.loaders.filesystem import Loader
from openedx.core.djangoapps.theming.helpers import get_current_theme
dirs = settings.DEFAULT_TEMPLATE_ENGINE['DIRS']
theme = get_current_theme()
if theme:
    dirs = list(dirs)
    dirs.append(theme.path / 'templates')
engine = Engine(dirs=dirs)
loader = Loader(engine)

source = None
for origin in loader.get_template_sources(path):
    try:
        source = loader.get_contents(origin)
    except TemplateDoesNotExist:
        pass

if not source:
    raise TemplateDoesNotExist(path)

%>${source | n, decode.utf8}</%def>

<%def name="webpack(entry, extension=None, config='DEFAULT', attrs='')">
    <%doc>
        Loads Javascript onto your page from a Webpack-generated bundle.
        Uses the Django template engine because our webpack loader only provides template tags for Jinja and Django.
    </%doc>
    <%
        body = capture(caller.body)
    %>
    ${HTML(render_bundle(context, entry, extension=None, config='DEFAULT', attrs=attrs))}
    % if body:
      <script type="text/javascript">
        ${body | n, decode.utf8}
      </script>
    % endif
</%def>

<%def name="renderReact(component, id, props={})">
    <%doc>
        Wrapper function to load a React component via webpack() and render
        it onto the page, passing an optional context object via props.
        component: (string) The component to render, as specified by the name
        of its Webpack entry point.
        id: (string) A unique id to apply to the component's container div.
        props: (dict, optional) An object containing data to pass into the
        component as props.
    </%doc>

    ${HTML(render_bundle(context, component))}
    ${HTML(render_bundle(context,'ReactRenderer'))}

    <div id="${id}"></div>
    <script type="text/javascript">
      var c;
      try { c = ${component | n, decode.utf8}; } catch (e) { c = null; }
      new ReactRenderer({
        component: c,
        selector: '#${id | n, decode.utf8}',
        componentName: '${component | n, js_escaped_string}',
        props: ${props | n, dump_js_escaped_json}
      });
    </script>
</%def>

<%def name="require_module(module_name, class_name)">
    <%doc>
      Loads Javascript onto your page synchronously.
      Uses RequireJS in development and a plain script tag in production.
      Use this form of require_module for all new code.
    </%doc>
    % if not settings.REQUIRE_DEBUG:
      <script type="text/javascript" src="${staticfiles_storage.url(module_name + '.js') + '?raw'}"></script>
    % endif
    <script type="text/javascript">
        (function (require) {
            require(['${module_name | n, js_escaped_string}'], function (${class_name | n, decode.utf8}) {
                ${caller.body() | n, decode.utf8}
            });
        }).call(this, require || RequireJS.require);
    </script>
</%def>

<%def name="require_module_async(module_name, class_name)">
  <%doc>
    Legacy mode of require_module that operates asynchronously, required for certain edge cases
    (notably where Javascript is required outside of a <%block name="js_extra" or "headextra").
    Do not use for any new code; instead create a factory and use require_module above.
  </%doc>
  <script type="text/javascript">
    (function (require) {
      % if settings.REQUIRE_DEBUG:
          (function (require) {
              require(['${module_name | n, js_escaped_string}'], function (${class_name | n, decode.utf8}) {
                  ${caller.body() | n, decode.utf8}
              });
          }).call(this, require || RequireJS.require);
      % else:
        ## The "raw" parameter is specified to avoid the URL from being further maninpulated by
        ## static_replace calls (as would happen if require_module is used within courseware).
        ## Without specifying "raw", a call to static_replace would result in the MD5 hash being
        ## being appended more than once, causing the import to fail in production environments.
        require(['${staticfiles_storage.url(module_name + ".js") + "?raw" | n, js_escaped_string}'], function () {
          require(['${module_name | n, js_escaped_string}'], function (${class_name | n, decode.utf8}) {
            ${caller.body() | n, decode.utf8}
          });
        });
      % endif
    }).call(this, require || RequireJS.require);
  </script>
</%def>

<%def name="optional_include_mako(file, is_theming_enabled=False)"><%
# http://stackoverflow.com/q/21219531
if is_theming_enabled:
    file = get_template_path(file)
try:
    tmpl = self.get_template(file)
except TemplateLookupException:
    pass
else:
    tmpl.render_context(context)
%></%def>


<%def name="get_page_title_breadcrumbs(*args)"><%
    return page_title_breadcrumbs(*args)
%></%def>

<%def name="get_platform_name()"><%
    return get_value('platform_name', settings.PLATFORM_NAME)
%></%def>

<%def name="get_value(val_name, default=None, **kwargs)"><%
    return get_value(val_name, default=default, **kwargs)
%></%def>

<%def name="get_template_path(relative_path, **kwargs)"><%
    return get_template_path(relative_path, **kwargs)
%></%def>

<%def name="is_request_in_themed_site()"><%
    return is_request_in_themed_site()
%></%def>

<%def name="get_tech_support_email_address()"><%
    return get_value('email_from_address', settings.TECH_SUPPORT_EMAIL)
%></%def>

<%def name="get_contact_email_address()"><%
    return get_value('email_from_address', settings.CONTACT_EMAIL)
%></%def>
